package com.chuanye.mydrawable.activitys;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;

import com.chuanye.mydrawable.R;
import com.chuanye.mydrawable.adapters.RepairInfoAdapter;
import com.chuanye.mydrawable.adapters.RereConAdapter;
import com.chuanye.mydrawable.adapters.SpinnerOneAdapter;
import com.chuanye.mydrawable.beans.City;
import com.chuanye.mydrawable.beans.RepairInfoBean;
import com.chuanye.mydrawable.json.LocalJson;
import com.chuanye.mydrawable.utils.DateUtils;
import com.chuanye.mydrawable.views.CustomHScrollView;
import com.chuanye.mydrawable.views.DateDialog;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

public class QueryRepairActivity extends AppCompatActivity implements View.OnClickListener{

    private Context mContext;
    private TextView query_region_tv;
    private EditText query_number_et;
    private TextView query_tv_starttime;
    private TextView query_tv_endtime;
    private Button query_btn_query;

    private List<RepairInfoBean.ListBean> listBeanList = new ArrayList<>();

    private String regionnum = "";//区县编号

    private List<City.CityBean> citylist = new ArrayList<>();//区县

    public long startTime = System.currentTimeMillis();
    public long endTime = System.currentTimeMillis();
    private ImageView query_iv_starttime;
    private ImageView query_iv_endtime;
    private ImageView query_number_iv;
    private ImageView query_region_iv;
    private TextView query_tv_no;
    private LinearLayout query_region_ll;
    private LinearLayout query_region_ll_hide;
    private ImageView query_iv_add;
    private ImageView query_iv_hide;

    private  boolean ishidequery = true;
    //private RepairInfoAdapter adapter;
    //private ListView query_lv;

    private int leftPos;//用于记录CustomHScrollView的初始位置
    private int topPos;
    CustomHScrollView mScrollView;
    private RelativeLayout mHead;//标题头
    private ListView repair_record_context_lv;
    private RereConAdapter adapter;
    private PopupWindow window;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_query_repair);
        mContext = this;

        //初始化控件
        initView();
        initcitydata();

        getRepairList("","","","");

    }

    private void initcitydata() {
        //区、县数据
        String str = LocalJson.city;
        Gson gson = new Gson();
        City city = gson.fromJson(str,City.class);
        citylist = city.getCity();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        query_region_tv = (TextView) findViewById(R.id.query_region_tv);//区县
        query_region_tv.setOnClickListener(this);
        query_number_et = (EditText) findViewById(R.id.query_number_et);//编号
        query_tv_starttime = (TextView) findViewById(R.id.query_tv_starttime);
        query_tv_starttime.setOnClickListener(this);
        query_tv_endtime = (TextView) findViewById(R.id.query_tv_endtime);
        query_tv_endtime.setOnClickListener(this);
        query_btn_query = (Button) findViewById(R.id.query_btn_query);//查询
        query_btn_query.setOnClickListener(this);

        //query_lv = (ListView) findViewById(R.id.query_lv);//listview

        query_region_iv = (ImageView) findViewById(R.id.query_region_iv);
        query_region_iv.setOnClickListener(this);
        query_iv_starttime = (ImageView) findViewById(R.id.query_iv_starttime);
        query_iv_starttime.setOnClickListener(this);
        query_iv_endtime = (ImageView) findViewById(R.id.query_iv_endtime);
        query_iv_endtime.setOnClickListener(this);
        query_number_iv = (ImageView) findViewById(R.id.query_number_iv);
        query_number_iv.setOnClickListener(this);

        query_tv_no = (TextView) findViewById(R.id.query_tv_no);//无数据时显示

        query_region_ll = (LinearLayout) findViewById(R.id.query_region_ll);//区县LinearLayout 为了显示popwindow的宽

        //总查询布局
        query_region_ll_hide = (LinearLayout) findViewById(R.id.query_region_ll_hide);


        query_iv_add = (ImageView) findViewById(R.id.query_iv_add);
        query_iv_add.setOnClickListener(this);
        query_iv_hide = (ImageView) findViewById(R.id.query_iv_hide);
        query_iv_hide.setOnClickListener(this);

        //listview
        repair_record_context_lv = (ListView) findViewById(R.id.repair_record_context_lv);
        mScrollView = (CustomHScrollView) findViewById(R.id.h_scrollView);
        mHead = (RelativeLayout) findViewById(R.id.head_layout);
        mHead.setBackgroundResource(R.color.white);

        mHead.setFocusable(true);
        mHead.setClickable(true);
        mHead.setOnTouchListener(new MyTouchLinstener());
        repair_record_context_lv.setOnTouchListener(new MyTouchLinstener());


        repair_record_context_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Log.i("点击了：",""+listBeanList.get(i).getRepairId());
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.query_btn_query://查询
                String operator = query_number_et.getText().toString().trim();
                String indistinct = regionnum;
                String startRepairTime = query_tv_starttime.getText().toString().trim();
                String endRepairTime = query_tv_endtime.getText().toString().trim();

                if (listBeanList!=null && listBeanList.size() > 0){
                    listBeanList.clear();
                }

                getRepairList(indistinct,startRepairTime,endRepairTime,operator);

                query_region_ll_hide.setVisibility(View.GONE);
                ishidequery = true;
                query_iv_hide.setImageResource(R.drawable.img_down);
                break;
            case R.id.query_region_tv://区县
                showPopupWindow(view);
                break;
            case R.id.query_tv_starttime://开始时间
                DateDialog startDialog = new DateDialog(this, startTime, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, final int year, final int monthOfYear, final int dayOfMonth) {
                        /*TimeDialog timeDialog = new TimeDialog(MPChartActivity.this, startTime, new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                int m = monthOfYear + 1;
                                try {
                                    startTime = DateUtils.getStringTime("yyyy-MM-dd HH:mm", (year + "-" + m + "-" + dayOfMonth + " " + hourOfDay + ":" + minute));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                tv_starttime.setText(DateUtils.getFromat("yyyy-MM-dd HH:mm", startTime));
                            }
                        });
                        timeDialog.show();*/

                        int m = monthOfYear + 1;
                        try {
                            startTime = DateUtils.getStringTime("yyyy-MM-dd", (year + "-" + m + "-" + dayOfMonth));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        query_tv_starttime.setText(DateUtils.getFromat("yyyy-MM-dd", startTime));
                        Log.i("时间：",""+query_tv_starttime.getText().toString().trim());
                    }
                });
                startDialog.show();
                break;
            case R.id.query_tv_endtime://结束时间
                DateDialog endDialog = new DateDialog(this, endTime, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, final int year, final int monthOfYear, final int dayOfMonth) {
                        /*TimeDialog timeDialog = new TimeDialog(MPChartActivity.this, endTime, new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                int m = monthOfYear + 1;
                                try {
                                    endTime = DateUtils.getStringTime("yyyy-MM-dd HH:mm", (year + "-" + m + "-" + dayOfMonth + " " + hourOfDay + ":" + minute));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                tv_endtime.setText(DateUtils.getFromat("yyyy-MM-dd HH:mm", endTime));
                            }
                        });
                        timeDialog.show();*/

                        int m = monthOfYear + 1;
                        try {
                            endTime = DateUtils.getStringTime("yyyy-MM-dd", (year + "-" + m + "-" + dayOfMonth));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        query_tv_endtime.setText(DateUtils.getFromat("yyyy-MM-dd", endTime));
                    }
                });
                endDialog.show();
                break;
            case R.id.query_region_iv:
                query_region_tv.setText("");
                regionnum = "";//编号
                break;
            case R.id.query_iv_starttime:
                query_tv_starttime.setText("");
                break;
            case R.id.query_iv_endtime:
                query_tv_endtime.setText("");
                break;
            case R.id.query_number_iv:
                query_number_et.setText("");

                break;

            case R.id.query_iv_hide:

                if (ishidequery){
                    query_region_ll_hide.setVisibility(View.VISIBLE);
                    ishidequery = false;
                    query_iv_hide.setImageResource(R.drawable.img_up);
                }else {
                    query_region_ll_hide.setVisibility(View.GONE);
                    ishidequery = true;
                    query_iv_hide.setImageResource(R.drawable.img_down);
                }
                /*if (ishidequery){
                    showQueryRepairPopwindow(view);
                    ishidequery = false;
                    query_iv_hide.setImageResource(R.drawable.img_up);
                }else {
                    window.dismiss();
                    ishidequery = true;
                    query_iv_hide.setImageResource(R.drawable.img_down);
                }*/
                break;
            case R.id.query_iv_add:
                Intent intent = new Intent(mContext,CreateRepairsActivity.class);
                startActivity(intent);

                break;



        }


    }

    /*private void showQueryRepairPopwindow(View view){
        View view1 = LayoutInflater.from(mContext).inflate(R.layout.queryrepair_popwindow,null);
        query_region_tv = (TextView) view1.findViewById(R.id.query_region_tv);//区县
        query_region_tv.setOnClickListener(this);
        query_number_et = (EditText) view1.findViewById(R.id.query_number_et);//编号
        query_tv_starttime = (TextView) view1.findViewById(R.id.query_tv_starttime);
        query_tv_starttime.setOnClickListener(this);
        query_tv_endtime = (TextView) view1.findViewById(R.id.query_tv_endtime);
        query_tv_endtime.setOnClickListener(this);
        query_btn_query = (Button) view1.findViewById(R.id.query_btn_query);//查询
        query_btn_query.setOnClickListener(this);

        //query_lv = (ListView) findViewById(R.id.query_lv);//listview

        query_region_iv = (ImageView) view1.findViewById(R.id.query_region_iv);
        query_region_iv.setOnClickListener(this);
        query_iv_starttime = (ImageView) view1.findViewById(R.id.query_iv_starttime);
        query_iv_starttime.setOnClickListener(this);
        query_iv_endtime = (ImageView) view1.findViewById(R.id.query_iv_endtime);
        query_iv_endtime.setOnClickListener(this);
        query_number_iv = (ImageView) view1.findViewById(R.id.query_number_iv);
        query_number_iv.setOnClickListener(this);

        query_tv_no = (TextView) view1.findViewById(R.id.query_tv_no);//无数据时显示

        query_region_ll = (LinearLayout) view1.findViewById(R.id.query_region_ll);//区县LinearLayout 为了显示popwindow的宽

        //总查询布局
        query_region_ll_hide = (LinearLayout) view1.findViewById(R.id.query_region_ll_hide);
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;         // 屏幕宽度（像素）

        window = new PopupWindow(view1, width, 1000, true);
        window.setTouchable(true);
        window.showAsDropDown(view);

        query_region_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupWindow(view);
            }
        });
        query_tv_starttime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DateDialog startDialog = new DateDialog(mContext, startTime, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, final int year, final int monthOfYear, final int dayOfMonth) {


                        int m = monthOfYear + 1;
                        try {
                            startTime = DateUtils.getStringTime("yyyy-MM-dd", (year + "-" + m + "-" + dayOfMonth));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        query_tv_starttime.setText(DateUtils.getFromat("yyyy-MM-dd", startTime));
                        Log.i("时间：",""+query_tv_starttime.getText().toString().trim());
                    }
                });
                startDialog.show();
            }
        });
    }*/


    /**
     * 弹出Popwindow  选择区县
     * @param view
     */
    private void showPopupWindow(View view) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.region_popwindow, null);
        //contentView.setBackgroundColor(Color.WHITE);
        contentView.setBackgroundResource(R.drawable.edittext_bg);
        // 设置按钮的点击事件
        ListView listview = (ListView) contentView.findViewById(R.id.region_pop_listview);
        SpinnerOneAdapter adapter = new SpinnerOneAdapter(mContext,citylist);

        //final PopupWindow popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        //final PopupWindow popupWindow = new PopupWindow(contentView, 500, 300, true);
        final PopupWindow popupWindow = new PopupWindow(contentView, query_region_ll.getWidth(), 600, true);
        listview.setAdapter(adapter);
        popupWindow.setTouchable(true);

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                Log.i("mengdd", "onTouch : ");

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });

        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        //popupWindow.setBackgroundDrawable(getResources().getDrawable(Color.BLACK));
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
        // 设置好参数之后再show
        popupWindow.showAsDropDown(view);
        adapter.setSubClickListener(new SpinnerOneAdapter.SubClickListener() {
            @Override
            public void OntopicClickListener(View view, City.CityBean.CountyBean been, int position) {
                Log.i("选择区县：",been.getName()+" ,"+been.getNumber());
               query_region_tv.setText(been.getName());
               regionnum = been.getNumber();
                //关闭popwindow
                popupWindow.dismiss();




            }
        });
    }


    /**
     * 获得报修数据列表
     */
    private void getRepairList(String indistinct,String startRepairTime,String endRepairTime,String operator) {
        Log.i("查询参数：","区县编号indistinct："+indistinct+"，开始时间："+startRepairTime+"， 结束时间："+endRepairTime+", 编号："+operator);
        OkHttpUtils.get()
                .url("http://172.16.2.77:9001/api/RepairInfo")//用户登陆并做与设备关系处理
                .addParams("request.pageIndex", "1")//ZMX  LXQ
                .addParams("request.pagesSize", String.valueOf(Integer.MAX_VALUE))//q123456

                .addParams("request.indistinct", indistinct)//经营者  区县编号
                .addParams("request.startRepairTime", startRepairTime)//2019-01-31
                .addParams("request.endRepairTime", endRepairTime)//2019-01-31
                .addParams("request.operator", operator)// 模糊查询 编号
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(okhttp3.Call call, Exception e, int id) {
                        Log.i("请求异常：",e.toString());
                        query_tv_no.setVisibility(View.VISIBLE);
                        query_tv_no.setText("请求异常");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("查询报修列表请求数据：",response.toString());
                        Gson gson = new Gson();
                        String str = response.toString();
                        RepairInfoBean repairInfoBean = gson.fromJson(str,RepairInfoBean.class);
                        if (repairInfoBean != null && repairInfoBean.getList().size() > 0){
                            Log.i("刷新条数：",repairInfoBean.getList().size()+"");
                            listBeanList = repairInfoBean.getList();
                           /* adapter = new RepairInfoAdapter(mContext,listBeanList);
                            query_lv.setAdapter(adapter);*/
                            adapter = new RereConAdapter(mContext,listBeanList,mHead);
                            repair_record_context_lv.setAdapter(adapter);

                        }else {
                            query_tv_no.setVisibility(View.VISIBLE);
                           /* if (adapter!= null){
                                adapter.notifyDataSetChanged();
                            }*/

                           if (adapter != null){
                               adapter.notifyDataSetChanged();
                           }

                        }

                    }
                });
    }


    /**
     * 记录CustomHScrollView的初始位置
     * @param l
     * @param t
     */
    public void setPosData(int l, int t){
        this.leftPos = l;
        this.topPos = t;
    }

    class MyTouchLinstener implements View.OnTouchListener {

        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            //当在表头和listView控件上touch时，将事件分发给 ScrollView
            HorizontalScrollView headSrcrollView = (HorizontalScrollView) mHead.findViewById(R.id.h_scrollView);
            headSrcrollView.onTouchEvent(arg1);
            return false;
        }
    }
}
